import { defineStore } from 'pinia';
import { reqLogin, reqUserInfo, reqLogout } from '@/api/user/index';
import { SET_TOKEN, GET_TOKEN, REMOVE_TOKEN } from '@/utils/token';
import { constantRoute, anyRoute, asyncRoute } from '@/router/router';
// pinia中无法直接使用useRoute、useRouter，可以导入router示例
// 通过对实例push/replace可以实现跳转，router.currentRoute.value可以拿到当前路由信息
import router from '@/router';
import type { UserState } from './types/type';
import type { loginForm, loginResponseData, userResponseData } from '@/api/user/type';

import cloneDeep from 'lodash/cloneDeep';

//筛选当前用户需要展示的异步路由
function filterAsyncRoute(asyncRoute: any, routes: any) {
  return asyncRoute.filter((item: any) => {
    if (routes.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(item.children, routes);
      }
      return true;
    }
  });
}

let useUserStore = defineStore('User', {
  //用户数据存储
  state: (): UserState => {
    return {
      token: GET_TOKEN(),
      menuRoutes: constantRoute,
      username: '',
      avatar: '',
      buttons: [],
    };
  },
  //异步|逻辑处理
  actions: {
    async userLogin(data: loginForm) {
      let result: loginResponseData = await reqLogin(data);
      if (result.code == 200) {
        this.token = result.data as string;
        SET_TOKEN(result.data as string);
        return Promise.resolve('登录成功');
      } else {
        return Promise.reject(result.data);
      }
    },
    async userInfo() {
      let result: userResponseData = await reqUserInfo();

      if (result.code == 200) {
        this.username = result.data.name;
        this.avatar = result.data.avatar;
        this.buttons = result.data.buttons;
        let userAsyncRoute = filterAsyncRoute(cloneDeep(asyncRoute), result.data.routes);
        this.menuRoutes = [...constantRoute, ...userAsyncRoute, ...anyRoute];
        [...userAsyncRoute, ...anyRoute].forEach((route: any) => {
          router.addRoute(route);
        });
        return 'ok';
      } else {
        return Promise.reject(result.message);
      }
    },

    async userLogout() {
      await reqLogout();
      // if (result.code === 200) {
      this.token = '';
      this.username = '';
      this.avatar = '';
      REMOVE_TOKEN();
      router.push({ path: '/login', query: { redirect: router.currentRoute.value.path } });
      return 'ok';
      // } else {
      //   return Promise.reject(new Error(result.message));
      // }
    },
  },
  getters: {},
});

export default useUserStore;
